from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from pymongo import MongoClient
from time import sleep
import time
import re
# from .config import *
import os

PLATFORM: "Android"
DEVICE_NAME: "SM_G9008V"  # 设备名称
APP_PACKAGE: "com.tencent.mm"
APP_ACTIVITY: " .ui.LauncherUI"

DRIVER_SERVER = 'http://localhost:4723/wd/hub'
TIMEOUT = 30

# 滑动点
FLICK_START_X = 300
FLICK_START_Y = 300
FLICK_DISTANCE = 700


class Moments():
    def __init__(self):
        """
        初始化
        """
        # 配置驱动
        self.desired_caps = {
            "platformName": 'Android',
            "deviceName": 'SM_G9008V',
            "appPackage": 'com.tencent.mm',
            "appActivity": '.ui.LauncherUI',
            # 'noReset': True
        }
        self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
        self.wait = WebDriverWait(self.driver, TIMEOUT)
        self.client = MongoClient(host='localhost', port=27017)
        self.db = self.client['moments']
        self.collection = self.db['moments']

    def login(self):
        """
        登录
        :return:
        """
        #登录按钮
        s1 = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@text="登录"]')))
        s1.click()
        # 手机号输入
        s2 = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/ji')))
        s2.set_text("18041385657")
        s3 = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/ast')))
        s3.click()
        # 密码
        s4 = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@text="密码"]')))
        s4.set_text("Zc13296814553")
        s3.click()
        s5 = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/au_')))
        s5.click()
        s6 = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@text="发现"]')))
        s6.click()
        s7 = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@text="朋友圈"]')))
        s7.click()

    def crawl(self):
        while True:
            # 显示元素
            items = self.wait.until(
                EC.presence_of_all_elements_located(
                    (By.XPATH, '//*[@resource-id="com.tencent.mm:id/e2p"]//android.widget.FrameLayout')))
            # 上划
            self.driver.swipe(300, 800, 300, 300)
            for item in items:
                try:
                    # 昵称
                    nickname = item.find_element_by_id('com.tencent.mm:id/azl').get_attribute('text')
                    # 正文
                    content = item.find_element_by_id('com.tencent.mm:id/e6x').get_attribute('text')
                    # 日期
                    date = item.find_element_by_id('com.tencent.mm:id/e25').get_attribute('text')
                    date = self.dates(date)
                    print(nickname, date)
                    data = {
                        'nickname': nickname,
                        'content': content,
                        'date': date,
                    }
                    # 将数据保存到MOngoDB
                    self.collection.update({'nickname': nickname, 'content': content}, {'$set': data}, True)
                    sleep(1)
                except NoSuchElementException:
                    pass
                except WebDriverException:
                    pass

    def dates(self, datetime):
        """
        处理时间
        :param datetime:
        :return:
        """
        if re.match('\d+分钟前', datetime):
            minute = re.match('(\d+)', datetime).group(1)
            datetime = time.strftime('%Y-%m-%d',time.localtime(time.time() - float(minute) * 60))
        if re.match('\d+小时前', datetime):
            hour = re.match('(\d+)', datetime).group(1)
            datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - float(hour) * 60 * 60))
        if re.match('昨天', datetime):
            datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))
        if re.match('\d+天前', datetime):
            day = re.match('(\d+)', datetime).group(1)
            datetime = time.strftime('%Y-%m-%d', time.localtime(time.time()) - float(day) * 24 * 60 * 60)
        return datetime



    def main(self):
        """
        入口
        :return:
        """
        # 登录
        self.login()
        # 爬取
        self.crawl()


if __name__ == '__main__':
    moments = Moments()
    moments.main()
